package com.hotelManager.www.service;

import com.hotelManager.www.dao.ShopDao;
import com.hotelManager.www.dao.UserDao;
import com.hotelManager.www.dao.OrderDao;
import com.hotelManager.www.dao.FavoritesDao;
import com.hotelManager.www.dao.RoomTypeDao;
import com.hotelManager.www.po.Favorites;
import com.hotelManager.www.po.Shop;
import com.hotelManager.www.po.User;
import com.hotelManager.www.po.RoomType;
import com.hotelManager.www.serviceInterface.ShopServiceInterface;
import com.hotelManager.www.util.JDBCUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;

public class ShopService implements ShopServiceInterface {
    private final ShopDao shopDao ;
    private final OrderDao orderDao;
    private final RoomTypeDao roomTypeDao = new RoomTypeDao();
    private final OrderService orderService = new OrderService();
    private final FavoritesDao favoritesDao = new FavoritesDao();


    public ShopService() {
        this.shopDao = new ShopDao();
        this.orderDao = new OrderDao();
    }

    @Override
    public Connection getConnection() {
        try {
            return JDBCUtils.getConnection();
        } catch (Exception e) {
            throw new RuntimeException("获取数据库连接失败", e);
        }
    }

    @Override
    public boolean create(Shop shop) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.Shopregister(shop, conn);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean update(Shop shop) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.update(conn, shop);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean delete(Integer id) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.delete(conn, id);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Shop findById(Integer id) { // 确保参数名称为 id
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取店铺简要信息（包含地址和联系方式等）
     * @param shopId 店铺ID
     * @return 包含简要信息的店铺对象
     */
    public Shop getShopBriefById(Integer shopId) {
        try {
            return shopDao.findShopBriefById(shopId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }


    @Override
    public boolean registerShop(Shop shop, User user) {
        Connection conn = null;
        try {
            conn = getConnection();
            conn.setAutoCommit(false);
            System.out.println("开始注册店铺：" + shop.getShopname());

            UserDao userDao = new UserDao();

            // 检查用户是否已存在
            User existingUser = userDao.getUserByUsername(conn, user.getUsername());
            if (existingUser == null) {
                System.out.println("店铺注册失败：用户不存在");
                conn.rollback();
                return false;
            }

            // 检查是否已有店铺
            Shop existingShop = shopDao.findByUserId(existingUser.getId());
            if (existingShop != null) {
                System.out.println("店铺注册失败：该用户已有店铺");
                conn.rollback();
                return false;
            }

            // 设置店铺的user_id
            shop.setUserId(existingUser.getId());

            // 设置默认值
            shop.setAuditStatus("pending");
            shop.setSalesVolume(0);
            shop.setPublishTime(new Date());
            shop.setRevenue(BigDecimal.ZERO);

            // 注册店铺
            if (!shopDao.Shopregister(shop, conn)) {
                System.out.println("店铺注册失败：数据库操作失败");
                conn.rollback();
                return false;
            }

            conn.commit();
            System.out.println("店铺注册成功：" + shop.getShopname());
            return true;
        } catch (SQLException e) {
            System.out.println("店铺注册失败：" + e.getMessage());
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            return false;
        } catch (Exception e) {
            System.out.println("店铺注册失败：系统错误");
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<Shop> getAllApprovedShops() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByAuditStatus(conn, "approved");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<Shop> getShopsBySalesVolume() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findAllOrderBySalesVolume(conn);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<Shop> getShopsByTime() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findAllOrderByPublishTime(conn);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<Shop> searchShops(String keyword) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByKeyword(conn, keyword);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public int countVisibleShopsByKeyword(String keyword) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.countByKeyword(conn, keyword);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 分页模糊查询店铺
    public List<Shop> searchShopsWithPagination(String keyword, int page, int pageSize) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByKeywordWithPagination(conn, keyword, page, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean updateShopSales(Integer shopId, Integer count) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.updateSalesVolume(shopId, count);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean updateShopStatus(Integer shopId, String status) {
        Connection conn = null;
        try {
            conn = getConnection();
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                return false;
            }
            shop.setStatus(status);
            return shopDao.update(conn, shop);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<Shop> getPendingShops() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByAuditStatus(conn, "pending");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean updateShopAuditStatus(Integer shopId, String auditStatus) {
        Connection conn = null;
        try {
            conn = getConnection();
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                return false;
            }
            shop.setAuditStatus(auditStatus);
            return shopDao.update(conn, shop);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Shop getShopByUsername(String username) {
        Connection conn = null;
        try {
            conn = getConnection();
            UserDao userDao = new UserDao();
            User user = userDao.getUserByUsername(conn, username);
            if (user == null) {
                System.out.println("未找到用户：" + username);
                return null;
            }
            System.out.println("找到用户：" + username + "，ID：" + user.getId());
            
            // 使用用户ID查找对应的店铺
            Shop shop = shopDao.findByUserId(user.getId());
            if (shop == null) {
                System.out.println("未找到与用户ID " + user.getId() + " 关联的店铺");
            } else {
                System.out.println("找到店铺：" + shop.getShopname() + "，ID：" + shop.getId());
            }
            return shop;
        } catch (SQLException e) {
            System.out.println("数据库操作异常：" + e.getMessage());
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            System.out.println("其他异常：" + e.getMessage());
            throw new RuntimeException(e);
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public Shop getShopByUserId(Integer userId) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 添加收藏
    public boolean addFavoriteShop(int userId, int shopId) {
        Connection conn = null;
        try {
            conn = getConnection();
            // 检查是否已收藏
            boolean exists = favoritesDao.existsByUserIdAndShopId(conn, userId, shopId);
            if (exists) {
                throw new IllegalStateException("该店铺已被收藏");
            }
            if (favoritesDao.addFavorite(conn, new Favorites(userId, shopId))) {
                return shopDao.updateFavoritesVolume(shopId, 1);
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 获取用户收藏的店铺
    public List<Shop> getFavoritesByUserId(int userId) {
        Connection conn = null;
        try {
            conn = getConnection();
            return favoritesDao.getFavoriteShopsByUserId(conn, userId);

        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    // 取消收藏
    public boolean removeFavoriteShop(int userId, int shopId) {
        Connection conn = null;
        try {
            conn = getConnection();
            if (favoritesDao.removeFavorite(conn, userId, shopId)) {
                return shopDao.updateFavoritesVolume(shopId, -1);
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    // 更新店铺浏览量
    public boolean updateViewCount(Integer shopId) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.updateViewCount(shopId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }



    public boolean toggleShopStatus(Integer shopId, String status) {
        Connection conn = null;
        try {
            conn = getConnection();
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                return false;
            }
            shop.setStatus(status);
            return shopDao.update(conn, shop);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean isShopBannedOrClosed(Integer shopId) {
        Connection conn = null;
        try {
            conn = getConnection();
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                return false;
            }
            String status = shop.getStatus();
            return "banned".equals(status) || "closed".equals(status);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public List<Shop> getVisibleShopsForCustomers() {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findAllVisibleShops(conn);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean banShop(Integer shopId) {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);
            
            // 1. 更新商家状态为banned
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                throw new IllegalArgumentException("Shop not found");
            }
            shop.setStatus("banned");
            boolean updateSuccess = shopDao.update(conn, shop);
            
            if (!updateSuccess) {
                conn.rollback();
                return false;
            }
            
            // 2. 处理已确认订单的退款
            orderService.refundOrdersForBannedShop(shopId);
            
            conn.commit();
            return true;
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public List<Shop> searchShopsWithPaginationAndSort(String keyword, int page, int pageSize, String sortField, String sortOrder) {
        Connection conn = null;
        try {
            conn = getConnection();
            return shopDao.findByKeywordWithPaginationAndSort(conn, keyword, page, pageSize, sortField, sortOrder);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
